package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
)

func PostJson(url string, data map[string]interface{}) string {
	client := &http.Client{}
	bytesData, _ := json.Marshal(data)
	fmt.Println(string(bytesData))
	req, _ := http.NewRequest("POST", url, bytes.NewReader(bytesData))
	req.Header.Set("Content-Type", "application/json")
	resp, _ := client.Do(req)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	res := string(body)
	fmt.Println(res)
	return res
}

func PostJsonString(url string, data string) string {
	client := &http.Client{}
	fmt.Println(data)
	req, _ := http.NewRequest("POST", url, bytes.NewReader([]byte(data)))
	req.Header.Set("Content-Type", "application/json")
	resp, _ := client.Do(req)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	res := string(body)
	fmt.Println(res)
	return res
}

func PostJsonWithHeader(url string, header map[string]string, data string) (string, int) {
	client := &http.Client{}
	req, _ := http.NewRequest("POST", url, bytes.NewReader([]byte(data)))
	req.Header.Set("Content-Type", "application/json")
	for key := range header {
		value := header[key]
		req.Header.Add(key, value)
	}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("PostJsonWithHeader网络请求失败：", err)
		return "", -1
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	res := string(body)
	return res, resp.StatusCode
}

func PostFormData(url string, header map[string]string, body map[string]string) (string, error) {

	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)
	for key := range body {
		value := body[key]
		_ = writer.WriteField(key, value)
	}
	err := writer.Close()
	if err != nil {
		fmt.Println(err)
		return "", err
	}

	client := &http.Client{}
	req, err := http.NewRequest("POST", url, payload)
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	for key := range header {
		value := header[key]
		req.Header.Add(key, value)
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	defer res.Body.Close()

	returnBody, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return "", err
	}

	return string(returnBody), nil
}
